package com.rising.face.ali.bishi.consumer;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2021/2/7 18:46
 */
public class ConAndProducer {

    private Lock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    private AtomicInteger sum = new AtomicInteger(0);

    public void consumer() {

        try {
            while (true) {
                lock.lock();
                //库存为空，进入等待
                while (sum.get() <= 0) {
                    System.out.println("库存为空，进入等待===============");
                    notEmpty.await();
                }
                System.out.println(Thread.currentThread().getName()+"消费者消费一个，余额：" + sum.decrementAndGet());
                //激活生产者
                notFull.signal();
                Thread.sleep(100);
                lock.unlock();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void producer() {

        try {
            while (true) {
                lock.lock();
                //库存已满，进入等待
                while (sum.get() >= 10) {
                    System.out.println("库存已满，进入等待-------------");
                    notFull.await();
                }
                System.out.println(Thread.currentThread().getName()+"生产者生产一个，余额：" + sum.incrementAndGet());
                notEmpty.signal();
                Thread.sleep(50);
                lock.unlock();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ConAndProducer conAndProducer = new ConAndProducer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                conAndProducer.producer();
            }
        }, "AA").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                conAndProducer.consumer();
            }
        }, "BB").start();
    }
}
